//
//  EditPhotoCategoryListView.m
//  BabyHelper
//
//  Created by  thomas on 11-8-27.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "EditPhotoAlbumListView.h"


@implementation EditPhotoAlbumListView
@synthesize selectedIndex;
@synthesize photoAlbumList;
#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	self.title = NSLocalizedString(@"Edit",@"");

	//set background image
	self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background"]];
	self.view.backgroundColor = [UIColor clearColor];
	//set navigation background color
	self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:navBarRed green:navBarGreen blue:navBarBlue alpha:navBarAlpha];
	
	 NSArray * items = [[NSArray alloc] initWithObjects: NSLocalizedString(@"Add", @""),NSLocalizedString(@"Del", @""), nil];
	 switcher = [[UISegmentedControl alloc] initWithItems: items];
	 switcher.segmentedControlStyle =  UISegmentedControlStyleBar;
	 [items release];
	 [switcher addTarget:self action:@selector(toggleEdit:)forControlEvents: UIControlEventValueChanged];
	 segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView: switcher];
	 self.navigationItem.rightBarButtonItem = segmentBarItem;
	
	 simpleBarItem = [[UIBarButtonItem alloc]
								 initWithTitle:NSLocalizedString(@"Done",@"")
								 style:UIBarButtonItemStyleBordered 
								 target:self
								 action:@selector(toggleDone)		
								 ];
	
	 photoAlbumList = [[NSMutableArray alloc]init];
	
	 dateFormatter = [[NSDateFormatter alloc] init];
	 [dateFormatter setDateFormat:DATE_TIME_FORMAT];
	 self.selectedIndex = [NSIndexPath indexPathWithIndex:0];
}


-(void)toggleEdit:(id)sender{
	UISegmentedControl* switchControl = sender;
		
	if(switchControl.selectedSegmentIndex == 1)
	{
		[self.tableView setEditing:!self.tableView.editing animated:YES];
				
		if (self.tableView.editing)
			self.navigationItem.rightBarButtonItem = simpleBarItem;
		else
			self.navigationItem.rightBarButtonItem = segmentBarItem;
	}
	else
	{
		EditPhotoAlbumView *childView = [[EditPhotoAlbumView alloc] initWithNibName:@"EditPhotoCategoryView" bundle:nil];
		//childView.currentBabyActivityEntry = nil;
		[self.navigationController pushViewController:childView animated:YES];
		[childView release];		
	}
}


-(void)toggleDone{
	//[switchControl setTitle:NSLocalizedString(@"Del", @"") forSegmentAtIndex:1];
	[self.tableView setEditing:NO animated:YES];
	self.navigationItem.rightBarButtonItem = segmentBarItem;

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	Dao *dao = [Dao getInstance];
	[photoAlbumList removeAllObjects];
	[dao QueryPhotoCategoryEntryWith:@"ORDER BY ID ASC" records:photoAlbumList];
	[self.tableView reloadData];
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [photoAlbumList count] + 1;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
	NSLog(@"row is %d",indexPath.row);
	if(indexPath.row == 0)
	{
		cell.textLabel.text       =  NSLocalizedString(@"Other photo album", @"");
		cell.detailTextLabel.text = [dateFormatter stringFromDate:[NSDate date]];				
	}
	else {
		int realRow = indexPath.row -1;
		PhotoAlbumEntry *entry = [photoAlbumList objectAtIndex:realRow];
		cell.textLabel.text       = entry.name;
		cell.detailTextLabel.text = [dateFormatter stringFromDate:entry.timestamp];		
	}
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
  if (editingStyle == UITableViewCellEditingStyleDelete) {
	 
	 self.selectedIndex = indexPath; 
	 UIAlertView *alert = [[UIAlertView alloc] init];
	 [alert setTitle:NSLocalizedString(@"Alert",@"")];
	 [alert setMessage:NSLocalizedString(@"Are you sure to delete all photos in selected album?", @"")];
	 [alert setDelegate:self];
	 [alert addButtonWithTitle:@"Yes"];
	 [alert addButtonWithTitle:@"No"];
	 [alert show];
	 [alert release];
   }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == 0)
	{
		if (selectedIndex.row == 0 ) {
			//delete 随手拍中的所有相片,但是不会删除 随手拍专辑
			//[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:selectedIndex] withRowAnimation:YES];	
			[self.tableView setEditing:NO animated:YES];
			return;
		}
		else {
			int realRow = [selectedIndex row] - 1;
			[self.photoAlbumList removeObjectAtIndex:realRow];
			[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:selectedIndex] withRowAnimation:YES];		
		}
		
		 // Delete the all photos with same category id
		 //Dao *dao = [Dao getInstance];
		 //[dao RemoveBabyActivityEntry:entry];
	}
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

	int realRow = indexPath.row -1;
	PhotoAlbumEntry *entry = [photoAlbumList objectAtIndex:realRow];
	BabyPhotoListView *childView = [[BabyPhotoListView alloc] initWithNibName:@"BabyPhotoListVIew" bundle:nil]; 

	if (indexPath.row == 0 ) {
		childView.whereClause = @"WHERE categoryID = 0 and thumpath != 'null' ORDER BY TIMESTAMP DESC";
	}
	else {
		childView.whereClause = [NSString stringWithFormat:@"WHERE categoryID = '%d' and thumpath != 'null' ORDER BY TIMESTAMP DESC",entry.index];
	}

	[self.navigationController pushViewController:childView animated:YES];
	[childView release];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}
@end

